package pl.com.sthaether.mc.config;

import javafx.embed.swing.SwingFXUtils;
import javafx.scene.SnapshotParameters;
import javafx.scene.control.TreeItem;
import javafx.scene.image.WritableImage;
import javafx.scene.transform.Scale;
import javafx.stage.FileChooser;
import org.geotools.data.shapefile.ShapefileDataStore;
import pl.com.sthaether.mc.MCApplication;
import pl.com.sthaether.mc.components.treetable.filterable.MCFilterableTreeTableNode;
import pl.com.sthaether.mc.engine.MCMap;
import pl.com.sthaether.mc.engine.MCMapFactory;
import pl.com.sthaether.mc.engine.data.MCMapDataObject;
import pl.com.sthaether.mc.exception.MCExceptionHandler;
import pl.com.sthaether.mc.main.toolbar.MCToolbar;
import pl.com.sthaether.mc.main.workspace.MCWorkspacePane;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;


public class MCCurrentState {

    private FileChooser fileChooser = new FileChooser();
    private MCMap currentMap = MCMapFactory.createEmptyMap();
    private File currentFile = null;
//    private Desktop desktop = Desktop.getDesktop();


    private MCCurrentState() {
    }

    public static MCCurrentState getInstance() {
        return MCCurrentHolder.INSTANCE;
    }

    public void loadFileAction() {
        fileChooser.setTitle("Choose map to load");
        File fileToLoad = fileChooser.showOpenDialog(MCApplication.getPrimaryStage());
        if (fileToLoad != null) {
            try {

                currentFile = fileToLoad;
                loadSHPMap();
                MCWorkspacePane.getInstance().registerNewContent(currentMap.getGroup());

            } catch (Exception e) {

                MCExceptionHandler.handleException(e);
            }
        }

    }

    private void loadSHPMap() {
        try {
            currentMap = MCMapFactory.createMapFromSHPFile(new ShapefileDataStore(new URL("file", "", currentFile.getPath())));
            List<TreeItem<MCFilterableTreeTableNode>> nodesList = new ArrayList<>();
            for (MCMapDataObject obj : currentMap.getData().getObjectsMap().values()) {
                nodesList.add(MCFilterableTreeTableNode.generateMapObjectTree(obj));
            }
            MCToolbar.getInstance().getTable().setTableData(nodesList);
        } catch (MalformedURLException e) {
            MCExceptionHandler.handleException(e);
        }
    }

    public void saveFileAsAction() {
        fileChooser.setTitle("Choose file to save");
        File fileToSave = fileChooser.showSaveDialog(MCApplication.getPrimaryStage());
        if (fileToSave != null) {

            currentFile = fileToSave;
        }

    }

    public void exportAction() {
        fileChooser.setTitle("Choose file to save");
        File fileToSave = fileChooser.showSaveDialog(MCApplication.getPrimaryStage());
        if (fileToSave != null) {
            // TODO #needToDo - need to complete
//            saveImage(fileToSave, MCWorkspacePane.getInstance().snapshot(new SnapshotParameters(), null));
            saveAsPng(fileToSave);
        }

    }

    private void saveImage(File fileToSave, WritableImage snapshot) {
//        BufferedImage image = SwingFXUtils.fromFXImage(snapshot, null);
        try {
//            ImageIO.write(image, "png", fileToSave);
            BufferedImage image = SwingFXUtils.fromFXImage(snapshot, new BufferedImage(800, 600, BufferedImage.TYPE_3BYTE_BGR)); // Get buffered image.
            BufferedImage imageRGB = new BufferedImage(Math.min(16384, image.getWidth()), image.getHeight(), BufferedImage.OPAQUE); // Remove alpha-channel from buffered image.
            Graphics2D graphics = imageRGB.createGraphics();
            graphics.drawImage(image, 0, 0, null);
            javax.imageio.ImageIO.write(imageRGB, "jpg", fileToSave);
            graphics.dispose();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void saveFileAction() {
        if (currentFile != null) {

        } else {
            saveFileAsAction();
        }
        // TODO #needToDo - need to complete
    }

    public void newFileAction() {
        currentFile = null;
        currentMap = MCMapFactory.createEmptyMap();
        // TODO #needToDo - need to complete
    }

    public MCMap getCurrentMap() {
        return currentMap;
    }


    private static class MCCurrentHolder {
        static final MCCurrentState INSTANCE = new MCCurrentState();
    }

    public void saveAsPng(File fileToSave) {
        SnapshotParameters param = new SnapshotParameters();
        param.setTransform(new Scale(5.0, 5.0));
        WritableImage image = MCWorkspacePane.getInstance().snapshot(param, null);
        try {
            javax.imageio.ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", fileToSave);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
